package com.dc.base.utils;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Rxjava异步任务
 *
 * @author 冰柠檬dc
 */
public class AsyncTask {

    private AsyncTask() {
    }

    private static class Holder {
        private static final AsyncTask INSTANCE = new AsyncTask();
    }

    public static AsyncTask getInstance() {
        return Holder.INSTANCE;
    }

    /**
     * 发起异步处理任务
     *
     * @param consumer Consumer
     * @return Disposable
     */
    public Disposable submit(Consumer<Object> consumer) {
        return submit(consumer, 0);
    }

    /**
     * 延迟发起异步处理任务
     *
     * @param consumer Consumer
     * @param delay    long
     * @return Disposable
     */
    public Disposable submit(Consumer<Object> consumer, long delay) {
        return Observable.timer(delay, TimeUnit.MILLISECONDS)
                .compose(RxJavaUtil.observableToMain())
                .subscribe(consumer);
    }

    /**
     * 发起异步处理任务
     *
     * @param observable Observable
     * @param consumer Consumer
     * @param <T> T
     * @return Disposable
     */
    public <T> Disposable submit(Observable<T> observable, Consumer<T> consumer) {
        return submit(observable, consumer, 0);
    }

    /**
     * 延迟发起异步处理任务
     *
     * @param observable Observable
     * @param consumer Consumer
     * @param delay long
     * @param <T> T
     * @return Disposable
     */
    public <T> Disposable submit(Observable<T> observable, Consumer<T> consumer, long delay) {
        return observable.delay(delay, TimeUnit.MILLISECONDS)
                .compose(RxJavaUtil.observableToMain())
                .subscribe(consumer, throwable -> {

                });
    }
}
